#!/usr/bin/env bash

if [ ! -n "${RMFILE}" ]; then
RMFILE="$(command -v rm) -rf"
fi

if [ ! -n "${PYTHON}" ]; then
PYTHON="$(command -v python)"
fi

if [ ! -n "${MKDIR}" ]; then
MKDIR="$(command -v mkdir) -v"
fi

if [ ! -n "${INSTALL}" ]; then
INSTALL="$(command -v install) -v -c"
fi

if [ ! -n "${PREFIX}" ]; then
PREFIX=$(${PYTHON} -c "from distutils.sysconfig import get_python_lib; print(get_python_lib());")
fi

printandrun() {
echo ${1}
eval ${1}
}

testandcreatedir() {
printandrun "test -z \"${1}\" || ${MKDIR} -p \"${1}\""
}

installpyfiles() {
printandrun "${INSTALL} \"${1}\" \"${2}\""
}

buildwithpy() {
printandrun "${PYTHON} -m compileall \"${PREFIX}/${1}\""
printandrun "${PYTHON} -O -m compileall \"${PREFIX}/${1}\""
}

OLDCWD="$(pwd)"
echo "Installing Python Moudle upcean";
echo "Checking for Python Moudle PIL"
${PYTHON} -c "import PIL"
if [ "$?" -ne "0" ]; then 
echo "Sorry could not find Python Moudle PIL";
exit 0; 
fi
echo "Checking for Python Moudle ReadLine"
${PYTHON} -c "import readline"
if [ "$?" -ne "0" ]; then 
echo "Sorry could not find Python Moudle ReadLine"; 
exit 0; 
fi
testandcreatedir "${PREFIX}/upcean"
for f in ./upcean/*; do  
installpyfiles "${f}" "${PREFIX}/upcean/$(basename ${f})"
done
printandrun "cd \"${PREFIX}\""
buildwithpy "upcean"
printandrun "cd \"${OLDCWD}\""
echo "Finished installing Python Moudle upcean";

